package com.foreverwin.mes.warehouse.service.impl;

import com.foreverwin.mes.common.enums.HandleEnum;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.foreverwin.mes.core.utils.DateUtil;
import com.foreverwin.mes.warehouse.constant.Constants;
import com.foreverwin.mes.warehouse.dto.YieldStorageDto;
import com.foreverwin.mes.warehouse.mapper.YieldStorageMapper;
import com.foreverwin.mes.warehouse.model.YieldConfirm;
import com.foreverwin.mes.warehouse.service.YieldConfirmService;
import com.foreverwin.mes.warehouse.service.YieldStorageService;
import com.foreverwin.mes.warehouse.vo.YieldStorageVo;
import com.sap.me.extension.Services;
import com.sap.me.frame.transitionutils.Exceptions;
import com.sap.me.inventory.InventoryConsumeRequest;
import com.sap.me.inventory.InventoryServiceInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author Ervin Chen
 * @date 2020/2/14 16:26
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class YieldStorageServiceImpl implements YieldStorageService {

    @Autowired
    private YieldStorageMapper yieldStorageMapper;
    @Autowired
    private YieldConfirmService yieldConfirmService;

    @Override
    public List<YieldStorageVo> selectInventoryList(YieldStorageDto yieldStorageDto) {
        String site = CommonMethods.getSite();
        String workCenter = yieldStorageDto.getWorkCenter();
        Date startDate = yieldStorageDto.getStartDate();
        Date endDate = yieldStorageDto.getEndDate();

        if (startDate != null && endDate != null && startDate.after(endDate)) {
            throw BusinessException.build("warehouse.yieldStorage.startDateAfterEndDate", DateUtil.format(startDate, "yyyy-MM-dd"), DateUtil.format(endDate, "yyyy-MM-dd"));
        }

        Locale locale = LocaleContextHolder.getLocale();
        return yieldStorageMapper.selectInventoryList(locale.getLanguage(), site,
                Constants.MANUFACTURING_ITEM_TYPE, workCenter,
                startDate, endDate);
    }

    @Override
    public boolean insertOrUpdate(List<YieldStorageDto> yieldStorageDtos) {
        String site = CommonMethods.getSite();
        String userBo = CommonMethods.getUserBo();
        Date now = new Date();

        for (YieldStorageDto yieldStorageDto : yieldStorageDtos) {
            validateFields(yieldStorageDto);
        }

        for (YieldStorageDto yieldStorageDto : yieldStorageDtos) {
            String inventoryId = yieldStorageDto.getInventoryId();
            String workCenter = yieldStorageDto.getWorkCenter();
            String itemBo = yieldStorageDto.getItemBo();
            String unitOfMeasure = yieldStorageDto.getUnitOfMeasure();
            Double originalQty = yieldStorageDto.getOriginalQty();
            Double qty = yieldStorageDto.getQty();

            //保存成品入库申请
            YieldConfirm yieldConfirm = new YieldConfirm();
            yieldConfirm.setHandle(HandleEnum.YIELD_CONFIRM.getHandle(site, inventoryId, DateUtil.format(now)));
            yieldConfirm.setSite(site);
            yieldConfirm.setInventoryId(inventoryId);
            yieldConfirm.setWorkCenter(workCenter);
            yieldConfirm.setItemBo(itemBo);
            yieldConfirm.setUnitOfMeasure(unitOfMeasure);
            yieldConfirm.setOriginalQty(originalQty);
            yieldConfirm.setQty(qty);
            yieldConfirm.setIsConfirmed(Constants.NOT_CONFIRMED);
            yieldConfirm.setCreateUserBo(userBo);
            yieldConfirm.setCreatedDateTime(now);
            yieldConfirmService.insert(yieldConfirm);

            //扣减ME库存
            InventoryServiceInterface inventoryServiceInterface = Services.getService("com.sap.me.inventory", "InventoryService", site);
            InventoryConsumeRequest consumeRequest = new InventoryConsumeRequest();
            consumeRequest.setInventoryRef(HandleEnum.INVENTORY.getHandle(site, inventoryId));
            consumeRequest.setComponentRef(itemBo);
            consumeRequest.setQty(BigDecimal.valueOf(qty));
            try {
                inventoryServiceInterface.consume(consumeRequest);
            } catch (com.sap.me.frame.domain.BusinessException e) {
                throw BusinessException.build(Exceptions.convert(e).toString());
            }
        }

        return true;
    }

    public boolean validateFields(YieldStorageDto yieldStorageDto) {
        String inventoryId = yieldStorageDto.getInventoryId();
        Double qtyOnHand = yieldStorageDto.getQtyOnHand();
        Double qty = yieldStorageDto.getQty();

        if (qty == null || qty <= 0) {
            throw BusinessException.build("warehouse.yieldStorage.qtyNotBlankOrNotValid", inventoryId, qty);
        }
        if (qty > qtyOnHand) {
            throw BusinessException.build("warehouse.yieldStorage.qtyOverQtyOnHand", inventoryId, qty, qtyOnHand);
        }
        return true;
    }
}
